<template>
  <el-dialog
      top="5vh"
      width="95%"
      title="供应商报价对比表"
      :visible.sync="dialogValue"
      :close-on-click-modal="false"
      append-to-body
  >
    <div class="quote-comparison">
      <!-- 项目信息 -->
      <div class="bidding-info">
        <el-alert
          :title="`${currentBidding?.title || ''} - 报价对比`"
          type="info"
          :closable="false"
          show-icon
        >
          <div slot="description">
            <p>比价月份：{{ currentBidding?.month || '' }}</p>
            <p>官方参考价格菜品：{{ dishList.length }} 个 | 参与供应商：{{ supplierList.length }} 个</p>
            <p style="margin-top: 8px; font-size: 12px; color: #909399;">
              <i class="el-icon-info"></i> 表格说明：以官方参考价格菜品为主，显示各供应商的报价、差异、比例
            </p>
          </div>
        </el-alert>
      </div>

      <!-- 入围供应商选择和菜品管理 -->
      <div class="supplier-selection" style="margin-bottom: 20px;">
        <el-card shadow="never" size="small">
          <div slot="header" class="clearfix">
            <span style="font-weight: 600;">入围供应商选择</span>
            <el-button
              v-if="!isSupplierSelected"
              style="float: right; padding: 3px 0; margin-left: 10px;"
              type="text"
              @click="showSupplierSelection = true"
            >
              选择入围供应商
            </el-button>
            <el-button
              v-else
              style="float: right; padding: 3px 0; margin-left: 10px;"
              type="text"
              @click="showSupplierSelection = true"
            >
              修改入围供应商
            </el-button>

          </div>

          <div v-if="isSupplierSelected" class="selected-supplier-info">
            <el-tag type="success" size="medium">
              <i class="el-icon-check"></i>
              当前入围供应商：{{ selectedSupplierName }}
            </el-tag>
          </div>
          <div v-else class="no-supplier-info">
            <el-tag type="info" size="medium">
              <i class="el-icon-warning"></i>
              暂未选择入围供应商
            </el-tag>
          </div>
        </el-card>
      </div>

      <!-- 报价对比表格 -->
      <div class="comparison-table">
        <el-table
            size="small"
            stripe
            border
            v-loading="loading"
            :data="comparisonData"
            row-key="dish_id"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(255, 255, 255, 0.8)"
            max-height="600px"
        >
          <!-- 菜品信息列 -->
          <el-table-column prop="dish_category" label="菜品分类" width="120"  />
          <el-table-column prop="dish_name" label="菜品名称" width="150"  />
          <el-table-column prop="unit" label="单位" width="80"  />
          <el-table-column prop="base_price" label="官方参考价格" width="100"  align="center">
            <template slot-scope="scope">
              <span style="color: #409EFF; font-weight: bold;">¥{{ scope.row.base_price }}</span>
            </template>
          </el-table-column>

          <!-- 动态生成供应商报价列组 -->
          <el-table-column
            v-for="supplier in supplierList"
            :key="supplier.id"
            :label="supplier.name"
            align="center"
            width="180"
          >
            <!-- 报价列 -->
            <el-table-column
              :prop="`supplier_${supplier.id}_price`"
              label="报价"
              width="80"
              align="center"
            >
              <template slot-scope="scope">
                <div v-if="scope.row[`supplier_${supplier.id}`]" class="price-cell">
                  <span style="color: #E6A23C; font-weight: bold;">¥{{ scope.row[`supplier_${supplier.id}`].quoted_price }}</span>
                </div>
                <div v-else class="no-quote">
                  <span style="color: #C0C4CC;">-</span>
                </div>
              </template>
            </el-table-column>

            <!-- 差异列 -->
            <el-table-column
              :prop="`supplier_${supplier.id}_diff`"
              label="差异"
              width="60"
              align="center"
            >
              <template slot-scope="scope">
                <div v-if="scope.row[`supplier_${supplier.id}`]" class="diff-cell">
                  <span :class="getDiffClass(scope.row[`supplier_${supplier.id}`].diff)">
                    {{ formatDiff(scope.row[`supplier_${supplier.id}`].diff) }}
                  </span>
                </div>
                <div v-else class="no-quote">
                  <span style="color: #C0C4CC;">-</span>
                </div>
              </template>
            </el-table-column>

            <!-- 比例列 -->
            <el-table-column
              :prop="`supplier_${supplier.id}_percent`"
              label="比例"
              width="60"
              align="center"
            >
              <template slot-scope="scope">
                <div v-if="scope.row[`supplier_${supplier.id}`]" class="percent-cell">
                  <span :class="getDiffClass(scope.row[`supplier_${supplier.id}`].diff_percent)">
                    {{ formatPercent(scope.row[`supplier_${supplier.id}`].diff_percent) }}
                  </span>
                </div>
                <div v-else class="no-quote">
                  <span style="color: #C0C4CC;">-</span>
                </div>
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 供应商选择对话框 -->
    <el-dialog
      title="选择入围供应商"
      :visible.sync="showSupplierSelection"
      width="600px"
      :close-on-click-modal="false"
      append-to-body
    >
      <div class="supplier-selection-dialog">
        <el-alert
          title="重要提示"
          type="warning"
          :closable="false"
          show-icon
          style="margin-bottom: 20px;"
        >
          <div slot="description">
            <p>入围供应商确定后将无法修改，请谨慎选择！</p>
            <p>建议根据报价对比表的数据进行综合评估后选择。</p>
          </div>
        </el-alert>

        <div class="supplier-list">
          <h4>已报价供应商列表</h4>
          <el-radio-group v-model="selectedSupplierId" style="width: 100%;">
            <el-radio-button  v-for="supplier in supplierList" :key="supplier.id" :label="supplier.id">
                <span class="supplier-name">{{ supplier.name }}</span>
              </el-radio-button>
          </el-radio-group>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="showSupplierSelection = false">取消</el-button>
        <el-button
          type="primary"
          @click="confirmSupplierSelection"
          :disabled="!selectedSupplierId"
        >
          确认选择
        </el-button>
      </div>
    </el-dialog>


  </el-dialog>
</template>

<script>
import { http } from '@/api';

export default {
  name: 'QuoteList',
  data() {
    return {
      dialogValue: false,
      loading: false,
      currentBidding: null,
      dishList: [],
      supplierList: [],
      comparisonData: [],
      statisticsData: [],
      // 供应商选择相关
      showSupplierSelection: false,
      selectedSupplierId: null,
      quoteData: [], // 存储原始报价数据


    };
  },
  computed: {
    isSupplierSelected() {
      return this.currentBidding && this.currentBidding.selected_supplier_id;
    },
    selectedSupplierName() {
      if (!this.currentBidding || !this.currentBidding.selected_supplier_id) {
        return '';
      }
      const supplier = this.supplierList.find(s => s.id === this.currentBidding.selected_supplier_id);
      return supplier ? supplier.name : '';
    }
  },
  methods: {
    open(bidding) {
      this.currentBidding = bidding;
      this.dialogValue = true;
      this.loadQuoteData();
    },

    async loadQuoteData() {
      if (!this.currentBidding) return;

      this.loading = true;
      try {
        // 1. 获取官方参考价格菜品数据（以dish表为主）
        const dishRes = await http.dish.list({
          monthly_bidding_id: this.currentBidding.id
        });

        const dishData = dishRes.data || [];
        this.dishList = dishData.map(dish => ({
          dish_id: dish.id,
          dish_name: dish.name,
          dish_category: dish.category,
          unit: dish.unit,
          base_price: dish.base_price
        }));

        // 2. 获取供应商报价数据
        const quoteRes = await http.supplierQuote.list({
          monthly_bidding_id: this.currentBidding.id
        });

        const quoteData = quoteRes.data || [];
        this.quoteData = quoteData; // 保存原始数据

        // 3. 提取唯一的供应商
        const suppliers = new Map();

        quoteData.forEach(item => {
          // 收集供应商信息
          if (item.supplier) {
            suppliers.set(item.supplier.id, {
              id: item.supplier.id,
              name: item.supplier.name
            });
          }
        });

        this.supplierList = Array.from(suppliers.values());
        console.log('官方参考价格菜品数量:', this.dishList.length);
        console.log('供应商数量:', this.supplierList.length);
        console.log('报价数据数量:', quoteData.length);

        // 4. 构建对比数据
        this.buildComparisonData(quoteData);

        // 5. 构建统计数据
        this.buildStatisticsData(quoteData);

      } catch (error) {
        console.error('加载数据失败:', error);
      } finally {
        this.loading = false;
      }
    },

    buildComparisonData(quoteData) {
      // 以官方参考价格菜品为主，为每个菜品创建一行数据
      this.comparisonData = this.dishList.map(dish => {
        const rowData = {
          dish_id: dish.dish_id,
          dish_name: dish.dish_name,
          dish_category: dish.dish_category,
          unit: dish.unit,
          base_price: dish.base_price
        };

        // 为每个供应商添加报价信息
        this.supplierList.forEach(supplier => {
          const quote = quoteData.find(q =>
            q.dish_id === dish.dish_id && q.supplier_id === supplier.id
          );

          if (quote) {
            const diff = quote.quoted_price - dish.base_price;
            const diffPercent = dish.base_price > 0 ? ((diff / dish.base_price) * 100) : 0;

            rowData[`supplier_${supplier.id}`] = {
              quoted_price: quote.quoted_price,
              diff: diff,
              diff_percent: diffPercent
            };
          }
          // 如果供应商没有对该菜品的报价，则不添加该字段，表格会显示"未报价"
        });

        return rowData;
      });

      console.log('对比数据构建完成，菜品数量:', this.comparisonData.length);
    },

    buildStatisticsData(quoteData) {
      this.statisticsData = this.supplierList.map(supplier => {
        const supplierQuotes = quoteData.filter(q => q.supplier_id === supplier.id);
        const validQuotes = supplierQuotes.filter(q => q.quoted_price > 0);

        if (validQuotes.length === 0) {
          return {
            supplier_name: supplier.name,
            total_dishes: 0,
            avg_price: '0.00',
            total_amount: '0.00',
            avg_diff_percent: 0,
            coverage_rate: '0.00%'
          };
        }

        const totalAmount = validQuotes.reduce((sum, q) => sum + q.quoted_price, 0);
        const avgPrice = totalAmount / validQuotes.length;

        // 计算平均差异比例
        const totalDiffPercent = validQuotes.reduce((sum, q) => {
          const dish = this.dishList.find(d => d.dish_id === q.dish_id);
          if (dish && dish.base_price > 0) {
            const diff = q.quoted_price - dish.base_price;
            return sum + ((diff / dish.base_price) * 100);
          }
          return sum;
        }, 0);

        const avgDiffPercent = totalDiffPercent / validQuotes.length;

        // 计算覆盖率（报价菜品数 / 官方参考价格菜品总数）
        const coverageRate = (validQuotes.length / this.dishList.length * 100).toFixed(2);

        return {
          supplier_name: supplier.name,
          total_dishes: validQuotes.length,
          avg_price: avgPrice.toFixed(2),
          total_amount: totalAmount.toFixed(2),
          avg_diff_percent: avgDiffPercent,
          coverage_rate: coverageRate + '%'
        };
      });

      console.log('统计数据构建完成');
    },

    getDiffClass(value) {
      // 确保数值比较正确
      const numValue = parseFloat(value);
      if (numValue > 0) return 'diff-positive';
      if (numValue < 0) return 'diff-negative';
      return 'diff-zero';
    },

    formatDiff(diff) {
      const numDiff = parseFloat(diff);
      if (numDiff > 0) return `+¥${numDiff.toFixed(2)}`;
      if (numDiff < 0) return `¥${numDiff.toFixed(2)}`;
      return '¥0.00';
    },

    formatPercent(percent) {
      const numPercent = parseFloat(percent);
      if (numPercent > 0) return `+${numPercent.toFixed(2)}%`;
      if (numPercent < 0) return `${numPercent.toFixed(2)}%`;
      return '0.00%';
    },



    confirmSupplierSelection() {
      if (!this.selectedSupplierId) {
        this.$message.warning('请先选择入围供应商');
        return;
      }

      const selectedSupplier = this.supplierList.find(s => s.id === this.selectedSupplierId);
      if (!selectedSupplier) {
        this.$message.error('选择的供应商不存在');
        return;
      }

      // 二次确认
      this.$confirm(
        `确定选择 "${selectedSupplier.name}" 作为入围供应商吗？\n\n注意：确认后将无法修改！`,
        '确认选择入围供应商',
        {
          confirmButtonText: '确定选择',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: false
        }
      ).then(() => {
        this.submitSupplierSelection();
      }).catch(() => {
        // 用户取消
      });
    },

    async submitSupplierSelection() {
      try {
        // // 检查三家供应商时否都存在报价
        // const supplierQuotes = await http.supplierQuote.list({
        //   monthly_bidding_id: this.currentBidding.id,
        // });
        // let supplierList = []
        // supplierQuotes.forEach(item => {
        //   if (!supplierList.find(s => s === item.supplier_id)) {
        //     supplierList.push(item.supplier_id);
        //   }
        // });
        // if (supplierList.length !== this.supplierList.length) {
        //   this.$message.error('请确保所有供应商都存在报价');
        //   return;
        // }
        const res = await http.monthlyBidding.submitSupplier({
          id: this.currentBidding.id,
          selected_supplier_id: this.selectedSupplierId,
        });

        this.$message.success('入围供应商选择成功');

        // 更新当前比价项目信息
        this.currentBidding.selected_supplier_id = this.selectedSupplierId;

        this.showSupplierSelection = false;
        this.selectedSupplierId = null;

        // 通知父组件更新
        this.$emit('supplier-selected', this.currentBidding);

      } catch (error) {
        console.error('选择入围供应商失败:', error);
      }
    },


  }
};
</script>

<style lang="scss">
.quote-comparison {
  .bidding-info {
    margin-bottom: 20px;
  }

  .comparison-table {
    margin-bottom: 30px;
  }

  .statistics {
    h4 {
      margin-bottom: 15px;
      color: #303133;
    }
  }

  .price-cell {
    text-align: center;
    font-size: 14px;
  }

  .diff-cell {
    text-align: center;
    font-size: 12px;
  }

  .percent-cell {
    text-align: center;
    font-size: 12px;
  }

  .no-quote {
    text-align: center;
    color: #C0C4CC;
    font-size: 12px;
  }

  // 差异和百分比颜色样式
  .diff-positive {
    color: #F56C6C !important;
    font-weight: 500;
  }

  .diff-negative {
    color: #67C23A !important;
    font-weight: 500;
  }

  .diff-zero {
    color: #909399 !important;
    font-weight: 500;
  }

  // 供应商选择相关样式
  .supplier-selection {
    .selected-supplier-info {
      text-align: center;
      padding: 10px 0;
    }

    .no-supplier-info {
      text-align: center;
      padding: 10px 0;
    }
  }

  .supplier-selection-dialog {
    .supplier-list {
      h4 {
        margin-bottom: 15px;
        color: #303133;
      }
    }
  }


}
</style>
